from utils.electrode_ctrl import ElectrodeCtrl
import numpy as np
from time import sleep, perf_counter
from utils import pressure_recv_svr

def sleep_us(us: float):
    sleep(us / 1_000_000)

# Function to busy-wait for a specified number of microseconds
def busy_wait_us(us: float):
    end_time = perf_counter() + us / 1_000_000  # Calculate end time in seconds
    while perf_counter() < end_time:
        pass  # Busy-wait loop

if __name__ == '__main__':
    frame_open = np.zeros((8, 8))

    pattern = np.zeros((8, 8))

    # 电压和阈值设定
    N_threshold = 550  # 压力传感器阈值
    PW_min = 200  # 小脉冲宽度，对应小电压感知
    PW_max = 800  # 大脉冲宽度，对应大电压感知
    PW = PW_min
    PP_min = 1000  # 长脉冲周期，小脉冲频率，对应小电压感知 
    PP_max = 700  # 短脉冲周期，大脉冲频率，对应大电压感知
    PP = PP_min
    previous_pressure_g = 0.0

    # 启动压力传感器服务器
    pressure_recv_svr.start_pressure_recv_svr()

    pressure_data = []
    start_time = None   # Record the start time of the program

    while True:
        sleep(0.01)
        #current_time = perf_counter()
        pressure_g = pressure_recv_svr.global_data
        d_N = pressure_g - previous_pressure_g
        #previous_pressure_g = pressure_g

        if pressure_g > 30 and start_time == None:
            start_time = perf_counter()
            print("Pressure exceeded 30, starting measurement.")

        if start_time != None:
            current_time = perf_counter()
            if (current_time - start_time) < 5:
                print(f'Detected Pressure: {pressure_g}')

            # 记录程序开始后5-15秒的压力数据
            if 5 <= (current_time - start_time) <= 15:
                pressure_data.append(pressure_g)
                print(f'Detected Pressure: {pressure_g}')

            # 15秒后计算平均值并停止记录
            if current_time - start_time > 15:
                if pressure_data:
                    average_pressure = np.mean(pressure_data)
                    print(f'Average pressure between 5 and 15 seconds: {average_pressure}')
                #print(f'Detected Pressure: {pressure_g}')
                
                pressure_data = []  # Reset pressure data list





